﻿define('formActions',
    ['jquery', 'ko'],
    function($, ko) {
        var formActions = function(url, model) {
            var self = this;
            self.model = ko.observable(model);
            

            self.validation = function (responseText) {
                
                var obj = $.parseJSON(responseText);
                $.each(obj.modelState, function(key, value) {
                    var val = key;
                    val = val.replace("value.", "");
                    val = val.charAt(0).toLowerCase() + val.slice(1);
                    $.each(self.model(), function(keyi, valuei) {
                        if (keyi.toLowerCase() == val.toLowerCase() || keyi.toLowerCase() == val+"ObjName".toLowerCase()) {
                            valuei.hasError(true);
                            /* var convError = "could not convert";
                          if (value.toLowerCase().indexOf(convError) >= 0) value = "Please enter data in right format";*/
                            valuei.validationMessage(value);
                            return;
                        }
                    });
                });
            };

            self.clearValidation = function() {
                $.each(self.model(), function(key, value) {
                    try {
                        value.hasError(false);
                        value.validationMessage("");
                    } catch(e) {

                    }
                });
            };


            self.save = function(parent, dlg) {
                       
                self.clearValidation();
                var frm = ko.toJSON(self.model(), null, 2);
                $.ajax({
                    type: "POST",
                    url: "/Medora.Web" + url,
                    contentType: "application/json",
                    data: frm,
                    success: function(data) {
                        var m = self.model();
                        m.load(data);
                        parent.RefreshGrid();
                        dlg.close();
                        toastr.success("Data saved succesfully");
                        return true;
                    },
                    error: function(response) {
                        if (response.status == 400) {
                            self.validation(response.responseText);
                        }
                        return false;
                    }
                });
            };


        };
        return formActions;
    });